package com.aisino.efence.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.aisino.efence.model.SecretResult;
import com.aisino.efence.service.SecretService;
import com.aisino.efence.utils.OkhttpUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author fzc
 * @package com.aisino.efence.service.impl
 * @create 2018-04-09 14:00
 **/
@Service
public class SecretServiceImpl implements SecretService {

    private static final Logger LOG = LoggerFactory.getLogger(SecretServiceImpl.class);

    @Value("${hubei.key.url}")
    private String keyUrl;
    @Value("${secret.url}")
    private String secretUrl;


    @Override
    public String getKeyId() throws Exception {
        Response response = OkhttpUtil.okHttpGet(keyUrl);
        if (null != response) {
            String result = response.body().string();
            LOG.info("[step 2 文件加密]-[getKeyId]-[{}]" + result);
            SecretResult secretResult = JSON.parseObject(result, SecretResult.class);
            if (200 == secretResult.getCode()) {
                return secretResult.getData().get("keyId");
            }
        }
        return null;
    }

    @Override
    public String getSSKey(String id) throws Exception {
        Response response = OkhttpUtil.okHttpGet(secretUrl + id);
        if (null != response) {
            String result = response.body().string();
            LOG.info("[step 2 文件加密]-[getSSKey]-[{}]" + result);
            SecretResult secretResult = JSON.parseObject(result, SecretResult.class);
            if (200 == secretResult.getCode()) {
                return secretResult.getData().get("sskey");
            }
        }
        return null;
    }

    @Override
    public void encryptFile(String source, String target) throws Exception {
        try (FileInputStream fis = new FileInputStream(new File(source));
             FileOutputStream fos = new FileOutputStream(new File(target))) {
            LOG.info("[step 2 文件加密]-[encryptFile]-开始加密文件");
            //step 1 判断文件是否存在
            boolean exist = FileUtil.exist(source);
            if (!exist) {
                LOG.info("[step 2 文件加密]-[encryptFile]-文件不存在");
                throw new SecurityException("");
            }
            //step 2 获取keyId
            String keyId = getKeyId();
            if (StringUtils.isBlank(keyId)) {
                LOG.error("[step 2 文件加密]-[encryptFile]-获取keyID失败");
                throw new SecurityException("获取keyID失败");
            }
            //step 3 获取sskey
            String token = getSSKey(keyId);
            if (StringUtils.isBlank(token)) {
                LOG.error("[step 2 文件加密]-[encryptFile]-获取ssky失败");
                throw new SecurityException("获取ssky失败");
            }
            //step 4 加密文件
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, token.getBytes("UTF-8"));
            byte[] encrypt = aes.encrypt(fis);
            //step 4 生成文件
            fos.write(encrypt);
            LOG.info("[step 2 文件加密]-[encryptFile]-加密文件完成");
        } catch (Exception e) {
            e.printStackTrace();
            FileUtil.del(new File(target));
            LOG.error("[step 2 文件加密]-[encryptFile]-加密失败", e);
            throw new SecurityException("加密文件失败！");
        }
    }

    public static void main(String[] args) throws Exception {
        //step 1 读取文件
        try (FileInputStream fis = new FileInputStream(new File("/Users/fzc/Desktop/tmp/2017-02-c.csv"))) {
            //构建
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, "mzttkYIjbvDJDzFU".getBytes("UTF-8"));
            //加密
            byte[] encrypt = aes.decrypt(fis);

            FileOutputStream fos = new FileOutputStream(new File("/Users/fzc/Desktop/tmp/2017-02-ok.csv"));
            fos.write(encrypt);

//            CompressUtil.compressFileBy7z("/Users/fzc/Desktop/tmp/","2017-02-c.csv","/Users/fzc/Desktop/tmp/","2017-02.7z");
            /*//压缩
            InputStream is = Lz4Util.compressor(encrypt);
            //解压
            byte[] decompressed = Lz4Util.decompressed(is, encrypt.length);
            //解密
            byte[] decrypt = aes.decrypt(decompressed);

            try (FileOutputStream fos = new FileOutputStream(new File("D:\\测试上传ftp_201804111.txt"))) {
                fos.write(decrypt);
            } catch (Exception e) {
                e.printStackTrace();
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
